"""
智能告警服务
基于AI分析结果的智能告警系统，包括告警规则引擎、误报过滤、优先级管理等
"""
import asyncio
import logging
import json
from datetime import datetime, timedelta
from typing import List, Dict, Optional, Any, Callable
from uuid import uuid4
from collections import defaultdict, deque
from dataclasses import dataclass, field
from enum import Enum
import aiohttp

from schemas.ai_algorithm import (
    AlertRule, AlertEvent, AlertLevel, BehaviorType,
    BehaviorAnalysisResult, DetectionResult
)
from schemas.person_detection import PersonDetectionResult
from core.config import get_settings

logger = logging.getLogger(__name__)
settings = get_settings()


class AlertStatus(str, Enum):
    """告警状态枚举"""
    ACTIVE = "active"
    ACKNOWLEDGED = "acknowledged"
    RESOLVED = "resolved"
    SUPPRESSED = "suppressed"
    EXPIRED = "expired"


class NotificationType(str, Enum):
    """通知类型枚举"""
    EMAIL = "email"
    SMS = "sms"
    WEBHOOK = "webhook"
    PUSH = "push"
    SOUND = "sound"


@dataclass
class AlertCondition:
    """告警条件"""
    field: str
    operator: str  # >, <, >=, <=, ==, !=, in, not_in, contains
    value: Any
    duration: Optional[float] = None  # 持续时间要求（秒）
    
    def evaluate(self, data: Dict[str, Any]) -> bool:
        """评估条件"""
        try:
            field_value = self._get_field_value(data, self.field)
            
            if self.operator == ">":
                return field_value > self.value
            elif self.operator == "<":
                return field_value < self.value
            elif self.operator == ">=":
                return field_value >= self.value
            elif self.operator == "<=":
                return field_value <= self.value
            elif self.operator == "==":
                return field_value == self.value
            elif self.operator == "!=":
                return field_value != self.value
            elif self.operator == "in":
                return field_value in self.value
            elif self.operator == "not_in":
                return field_value not in self.value
            elif self.operator == "contains":
                return self.value in str(field_value)
            else:
                logger.warning(f"Unknown operator: {self.operator}")
                return False
                
        except Exception as e:
            logger.error(f"Error evaluating condition: {e}")
            return False
    
    def _get_field_value(self, data: Dict[str, Any], field_path: str) -> Any:
        """获取字段值，支持嵌套字段"""
        keys = field_path.split('.')
        value = data
        
        for key in keys:
            if isinstance(value, dict):
                value = value.get(key)
            elif isinstance(value, list) and key.isdigit():
                index = int(key)
                value = value[index] if 0 <= index < len(value) else None
            else:
                return None
        
        return value


@dataclass
class AlertRuleEngine:
    """告警规则引擎"""
    rule_id: str
    rule_name: str
    conditions: List[AlertCondition]
    alert_level: AlertLevel
    cooldown_period: int = 300  # 冷却期（秒）
    enabled: bool = True
    
    # 内部状态
    last_triggered: Optional[datetime] = None
    condition_states: Dict[str, deque] = field(default_factory=dict)
    
    def evaluate(self, data: Dict[str, Any]) -> bool:
        """评估规则"""
        if not self.enabled:
            return False
        
        # 检查冷却期
        if self.last_triggered:
            time_since_last = (datetime.now() - self.last_triggered).total_seconds()
            if time_since_last < self.cooldown_period:
                return False
        
        current_time = datetime.now()
        all_conditions_met = True
        
        for i, condition in enumerate(self.conditions):
            condition_key = f"condition_{i}"
            
            # 初始化条件状态
            if condition_key not in self.condition_states:
                self.condition_states[condition_key] = deque(maxlen=100)
            
            # 评估当前条件
            condition_met = condition.evaluate(data)
            self.condition_states[condition_key].append({
                'timestamp': current_time,
                'result': condition_met
            })
            
            # 检查持续时间要求
            if condition.duration and condition.duration > 0:
                # 检查在指定持续时间内条件是否一直满足
                duration_met = self._check_duration_requirement(
                    condition_key, condition.duration, current_time
                )
                if not duration_met:
                    all_conditions_met = False
                    break
            elif not condition_met:
                all_conditions_met = False
                break
        
        if all_conditions_met:
            self.last_triggered = current_time
        
        return all_conditions_met
    
    def _check_duration_requirement(
        self, 
        condition_key: str, 
        required_duration: float, 
        current_time: datetime
    ) -> bool:
        """检查持续时间要求"""
        states = self.condition_states[condition_key]
        if not states:
            return False
        
        # 查找最早满足条件的时间点
        earliest_satisfied = None
        for state in reversed(states):
            if state['result']:
                earliest_satisfied = state['timestamp']
            else:
                break
        
        if earliest_satisfied is None:
            return False
        
        # 检查持续时间
        duration = (current_time - earliest_satisfied).total_seconds()
        return duration >= required_duration


class FalsePositiveFilter:
    """误报过滤器"""
    
    def __init__(self):
        self.alert_history: Dict[str, List[datetime]] = defaultdict(list)
        self.confidence_threshold = 0.6
        self.frequency_threshold = 5  # 5分钟内超过此次数认为可能是误报
        self.time_window = 300  # 5分钟时间窗口
    
    def should_suppress_alert(self, alert_data: Dict[str, Any]) -> bool:
        """判断是否应该抑制告警"""
        # 基于置信度过滤
        confidence = alert_data.get('confidence', 1.0)
        if confidence < self.confidence_threshold:
            logger.info(f"Alert suppressed due to low confidence: {confidence}")
            return True
        
        # 基于频率过滤
        alert_type = alert_data.get('behavior_type', 'unknown')
        camera_id = alert_data.get('camera_id', 'unknown')
        alert_key = f"{camera_id}_{alert_type}"
        
        current_time = datetime.now()
        
        # 清理过期记录
        cutoff_time = current_time - timedelta(seconds=self.time_window)
        self.alert_history[alert_key] = [
            t for t in self.alert_history[alert_key] if t > cutoff_time
        ]
        
        # 检查频率
        if len(self.alert_history[alert_key]) >= self.frequency_threshold:
            logger.info(f"Alert suppressed due to high frequency: {alert_key}")
            return True
        
        # 记录当前告警
        self.alert_history[alert_key].append(current_time)
        return False
    
    def update_confidence_threshold(self, threshold: float):
        """更新置信度阈值"""
        self.confidence_threshold = max(0.0, min(1.0, threshold))
    
    def update_frequency_threshold(self, threshold: int):
        """更新频率阈值"""
        self.frequency_threshold = max(1, threshold)


class NotificationManager:
    """通知管理器"""
    
    def __init__(self):
        self.notification_handlers: Dict[NotificationType, Callable] = {
            NotificationType.EMAIL: self._send_email,
            NotificationType.SMS: self._send_sms,
            NotificationType.WEBHOOK: self._send_webhook,
            NotificationType.PUSH: self._send_push,
            NotificationType.SOUND: self._play_sound
        }
    
    async def send_notification(
        self, 
        notification_type: NotificationType,
        alert_event: AlertEvent,
        config: Dict[str, Any]
    ) -> bool:
        """发送通知"""
        try:
            handler = self.notification_handlers.get(notification_type)
            if handler:
                return await handler(alert_event, config)
            else:
                logger.warning(f"No handler for notification type: {notification_type}")
                return False
        except Exception as e:
            logger.error(f"Failed to send {notification_type} notification: {e}")
            return False
    
    async def _send_email(self, alert_event: AlertEvent, config: Dict[str, Any]) -> bool:
        """发送邮件通知"""
        # 这里应该集成实际的邮件服务
        recipients = config.get('recipients', [])
        subject = f"[{alert_event.alert_level.upper()}] {alert_event.title}"
        
        body = f"""
        告警详情:
        - 告警ID: {alert_event.alert_id}
        - 摄像头: {alert_event.camera_id}
        - 级别: {alert_event.alert_level}
        - 描述: {alert_event.description}
        - 时间: {alert_event.timestamp}
        """
        
        logger.info(f"Email notification sent to {recipients}: {subject}")
        return True
    
    async def _send_sms(self, alert_event: AlertEvent, config: Dict[str, Any]) -> bool:
        """发送短信通知"""
        # 这里应该集成实际的短信服务
        phone_numbers = config.get('phone_numbers', [])
        message = f"[{alert_event.alert_level.upper()}] {alert_event.title} - {alert_event.camera_id}"
        
        logger.info(f"SMS notification sent to {phone_numbers}: {message}")
        return True
    
    async def _send_webhook(self, alert_event: AlertEvent, config: Dict[str, Any]) -> bool:
        """发送Webhook通知"""
        webhook_url = config.get('url')
        if not webhook_url:
            return False
        
        payload = {
            'alert_id': alert_event.alert_id,
            'camera_id': alert_event.camera_id,
            'alert_level': alert_event.alert_level,
            'title': alert_event.title,
            'description': alert_event.description,
            'timestamp': alert_event.timestamp.isoformat(),
            'metadata': alert_event.metadata
        }
        
        try:
            async with aiohttp.ClientSession() as session:
                async with session.post(
                    webhook_url,
                    json=payload,
                    timeout=aiohttp.ClientTimeout(total=10)
                ) as response:
                    if response.status == 200:
                        logger.info(f"Webhook notification sent successfully to {webhook_url}")
                        return True
                    else:
                        logger.warning(f"Webhook notification failed: {response.status}")
                        return False
        except Exception as e:
            logger.error(f"Webhook notification error: {e}")
            return False
    
    async def _send_push(self, alert_event: AlertEvent, config: Dict[str, Any]) -> bool:
        """发送推送通知"""
        # 这里应该集成推送服务（如Firebase、APNs等）
        device_tokens = config.get('device_tokens', [])
        
        logger.info(f"Push notification sent to {len(device_tokens)} devices")
        return True
    
    async def _play_sound(self, alert_event: AlertEvent, config: Dict[str, Any]) -> bool:
        """播放声音告警"""
        sound_file = config.get('sound_file', 'default_alert.wav')
        volume = config.get('volume', 0.8)
        
        logger.info(f"Sound alert played: {sound_file} (volume: {volume})")
        return True


class IntelligentAlertService:
    """智能告警服务"""
    
    def __init__(self):
        self.alert_rules: Dict[str, AlertRuleEngine] = {}
        self.alert_events: Dict[str, AlertEvent] = {}
        self.false_positive_filter = FalsePositiveFilter()
        self.notification_manager = NotificationManager()
        
        # 服务状态
        self._running = False
        self._processing_task = None
        self._event_queue = asyncio.Queue()
        
        # 统计信息
        self.stats = {
            'total_alerts': 0,
            'suppressed_alerts': 0,
            'notifications_sent': 0,
            'rules_triggered': defaultdict(int)
        }
        
        # 初始化默认规则
        self._initialize_default_rules()
    
    def _initialize_default_rules(self):
        """初始化默认告警规则"""
        # 人员数量异常规则
        person_count_rule = AlertRuleEngine(
            rule_id="person_count_high",
            rule_name="人员数量过多告警",
            conditions=[
                AlertCondition("total_count", ">", 15, duration=30),
            ],
            alert_level=AlertLevel.HIGH,
            cooldown_period=300
        )
        self.alert_rules[person_count_rule.rule_id] = person_count_rule
        
        # 人群聚集规则
        crowding_rule = AlertRuleEngine(
            rule_id="crowding_detected",
            rule_name="人群聚集告警",
            conditions=[
                AlertCondition("behavior_type", "==", BehaviorType.CROWDING),
                AlertCondition("confidence", ">=", 0.7)
            ],
            alert_level=AlertLevel.MEDIUM,
            cooldown_period=180
        )
        self.alert_rules[crowding_rule.rule_id] = crowding_rule
        
        # 异常行为规则
        abnormal_behavior_rule = AlertRuleEngine(
            rule_id="abnormal_behavior",
            rule_name="异常行为告警",
            conditions=[
                AlertCondition("behavior_type", "in", [BehaviorType.FIGHTING, BehaviorType.RUNNING]),
                AlertCondition("confidence", ">=", 0.6)
            ],
            alert_level=AlertLevel.CRITICAL,
            cooldown_period=60
        )
        self.alert_rules[abnormal_behavior_rule.rule_id] = abnormal_behavior_rule
        
        # 徘徊行为规则
        loitering_rule = AlertRuleEngine(
            rule_id="loitering_detected",
            rule_name="徘徊行为告警",
            conditions=[
                AlertCondition("behavior_type", "==", BehaviorType.LOITERING),
                AlertCondition("duration", ">=", 120),  # 持续2分钟以上
                AlertCondition("confidence", ">=", 0.5)
            ],
            alert_level=AlertLevel.LOW,
            cooldown_period=600
        )
        self.alert_rules[loitering_rule.rule_id] = loitering_rule
    
    async def start_service(self):
        """启动告警服务"""
        if self._running:
            return
        
        self._running = True
        self._processing_task = asyncio.create_task(self._process_events())
        logger.info("Intelligent alert service started")
    
    async def stop_service(self):
        """停止告警服务"""
        self._running = False
        if self._processing_task:
            self._processing_task.cancel()
            try:
                await self._processing_task
            except asyncio.CancelledError:
                pass
        logger.info("Intelligent alert service stopped")
    
    async def _process_events(self):
        """处理事件队列"""
        while self._running:
            try:
                # 等待事件
                event_data = await asyncio.wait_for(
                    self._event_queue.get(), 
                    timeout=1.0
                )
                
                await self._handle_event(event_data)
                
            except asyncio.TimeoutError:
                continue
            except asyncio.CancelledError:
                break
            except Exception as e:
                logger.error(f"Error processing event: {e}")
    
    async def _handle_event(self, event_data: Dict[str, Any]):
        """处理单个事件"""
        try:
            # 评估所有规则
            triggered_rules = []
            
            for rule in self.alert_rules.values():
                if rule.evaluate(event_data):
                    triggered_rules.append(rule)
                    self.stats['rules_triggered'][rule.rule_id] += 1
            
            # 为每个触发的规则生成告警
            for rule in triggered_rules:
                await self._generate_alert(rule, event_data)
                
        except Exception as e:
            logger.error(f"Error handling event: {e}")
    
    async def _generate_alert(self, rule: AlertRuleEngine, event_data: Dict[str, Any]):
        """生成告警"""
        try:
            # 检查是否应该抑制告警
            if self.false_positive_filter.should_suppress_alert(event_data):
                self.stats['suppressed_alerts'] += 1
                return
            
            # 创建告警事件
            alert_event = AlertEvent(
                alert_id=str(uuid4()),
                rule_id=rule.rule_id,
                camera_id=event_data.get('camera_id', 'unknown'),
                alert_level=rule.alert_level,
                title=rule.rule_name,
                description=self._generate_alert_description(rule, event_data),
                timestamp=datetime.now(),
                metadata=event_data
            )
            
            # 存储告警事件
            self.alert_events[alert_event.alert_id] = alert_event
            self.stats['total_alerts'] += 1
            
            # 发送通知
            await self._send_notifications(alert_event)
            
            logger.info(f"Alert generated: {alert_event.alert_id} - {alert_event.title}")
            
        except Exception as e:
            logger.error(f"Error generating alert: {e}")
    
    def _generate_alert_description(self, rule: AlertRuleEngine, event_data: Dict[str, Any]) -> str:
        """生成告警描述"""
        behavior_type = event_data.get('behavior_type')
        total_count = event_data.get('total_count', 0)
        confidence = event_data.get('confidence', 0)
        
        if rule.rule_id == "person_count_high":
            return f"检测到人员数量异常：当前{total_count}人，超过阈值"
        elif rule.rule_id == "crowding_detected":
            return f"检测到人群聚集行为，置信度：{confidence:.2f}"
        elif rule.rule_id == "abnormal_behavior":
            return f"检测到异常行为：{behavior_type}，置信度：{confidence:.2f}"
        elif rule.rule_id == "loitering_detected":
            duration = event_data.get('duration', 0)
            return f"检测到徘徊行为，持续时间：{duration:.1f}秒"
        else:
            return f"触发告警规则：{rule.rule_name}"
    
    async def _send_notifications(self, alert_event: AlertEvent):
        """发送通知"""
        # 这里应该根据告警级别和配置决定发送哪些通知
        notification_configs = self._get_notification_configs(alert_event.alert_level)
        
        for notification_type, config in notification_configs.items():
            try:
                success = await self.notification_manager.send_notification(
                    notification_type, alert_event, config
                )
                if success:
                    self.stats['notifications_sent'] += 1
            except Exception as e:
                logger.error(f"Failed to send {notification_type} notification: {e}")
    
    def _get_notification_configs(self, alert_level: AlertLevel) -> Dict[NotificationType, Dict[str, Any]]:
        """获取通知配置"""
        configs = {}
        
        # 根据告警级别配置不同的通知方式
        if alert_level == AlertLevel.CRITICAL:
            configs[NotificationType.EMAIL] = {
                'recipients': ['admin@example.com', 'security@example.com']
            }
            configs[NotificationType.SMS] = {
                'phone_numbers': ['+1234567890']
            }
            configs[NotificationType.SOUND] = {
                'sound_file': 'critical_alert.wav',
                'volume': 1.0
            }
        elif alert_level == AlertLevel.HIGH:
            configs[NotificationType.EMAIL] = {
                'recipients': ['admin@example.com']
            }
            configs[NotificationType.WEBHOOK] = {
                'url': 'http://example.com/webhook/alerts'
            }
        elif alert_level == AlertLevel.MEDIUM:
            configs[NotificationType.WEBHOOK] = {
                'url': 'http://example.com/webhook/alerts'
            }
        # LOW级别告警只记录，不发送通知
        
        return configs
    
    async def process_detection_result(self, detection_result: PersonDetectionResult):
        """处理检测结果"""
        event_data = {
            'camera_id': detection_result.camera_id,
            'total_count': detection_result.total_count,
            'timestamp': detection_result.timestamp,
            'confidence': detection_result.confidence_threshold,
            'processing_time': detection_result.processing_time
        }
        
        await self._event_queue.put(event_data)
    
    async def process_behavior_result(self, behavior_result: BehaviorAnalysisResult):
        """处理行为分析结果"""
        event_data = {
            'camera_id': behavior_result.camera_id,
            'behavior_type': behavior_result.behavior_type,
            'confidence': behavior_result.confidence,
            'duration': behavior_result.duration,
            'timestamp': behavior_result.timestamp,
            'involved_tracks': behavior_result.involved_tracks,
            'metadata': behavior_result.metadata
        }
        
        await self._event_queue.put(event_data)
    
    def add_alert_rule(self, rule_config: Dict[str, Any]) -> str:
        """添加告警规则"""
        rule_id = rule_config.get('rule_id', str(uuid4()))
        
        # 解析条件
        conditions = []
        for cond_config in rule_config.get('conditions', []):
            condition = AlertCondition(
                field=cond_config['field'],
                operator=cond_config['operator'],
                value=cond_config['value'],
                duration=cond_config.get('duration')
            )
            conditions.append(condition)
        
        # 创建规则引擎
        rule = AlertRuleEngine(
            rule_id=rule_id,
            rule_name=rule_config['rule_name'],
            conditions=conditions,
            alert_level=AlertLevel(rule_config['alert_level']),
            cooldown_period=rule_config.get('cooldown_period', 300),
            enabled=rule_config.get('enabled', True)
        )
        
        self.alert_rules[rule_id] = rule
        logger.info(f"Added alert rule: {rule_id}")
        
        return rule_id
    
    def remove_alert_rule(self, rule_id: str) -> bool:
        """移除告警规则"""
        if rule_id in self.alert_rules:
            del self.alert_rules[rule_id]
            logger.info(f"Removed alert rule: {rule_id}")
            return True
        return False
    
    def update_alert_rule(self, rule_id: str, updates: Dict[str, Any]) -> bool:
        """更新告警规则"""
        if rule_id not in self.alert_rules:
            return False
        
        rule = self.alert_rules[rule_id]
        
        if 'enabled' in updates:
            rule.enabled = updates['enabled']
        if 'cooldown_period' in updates:
            rule.cooldown_period = updates['cooldown_period']
        if 'alert_level' in updates:
            rule.alert_level = AlertLevel(updates['alert_level'])
        
        logger.info(f"Updated alert rule: {rule_id}")
        return True
    
    def get_alert_rules(self) -> List[Dict[str, Any]]:
        """获取所有告警规则"""
        rules = []
        for rule in self.alert_rules.values():
            rule_data = {
                'rule_id': rule.rule_id,
                'rule_name': rule.rule_name,
                'alert_level': rule.alert_level.value,
                'cooldown_period': rule.cooldown_period,
                'enabled': rule.enabled,
                'last_triggered': rule.last_triggered.isoformat() if rule.last_triggered else None,
                'conditions': [
                    {
                        'field': cond.field,
                        'operator': cond.operator,
                        'value': cond.value,
                        'duration': cond.duration
                    }
                    for cond in rule.conditions
                ]
            }
            rules.append(rule_data)
        
        return rules
    
    def get_alert_events(
        self, 
        camera_id: Optional[str] = None,
        alert_level: Optional[AlertLevel] = None,
        status: Optional[AlertStatus] = None,
        start_time: Optional[datetime] = None,
        end_time: Optional[datetime] = None,
        limit: int = 100
    ) -> List[AlertEvent]:
        """获取告警事件"""
        events = list(self.alert_events.values())
        
        # 过滤条件
        if camera_id:
            events = [e for e in events if e.camera_id == camera_id]
        
        if alert_level:
            events = [e for e in events if e.alert_level == alert_level]
        
        if start_time:
            events = [e for e in events if e.timestamp >= start_time]
        
        if end_time:
            events = [e for e in events if e.timestamp <= end_time]
        
        # 按时间倒序排列
        events.sort(key=lambda x: x.timestamp, reverse=True)
        
        return events[:limit]
    
    def acknowledge_alert(self, alert_id: str, acknowledged_by: str) -> bool:
        """确认告警"""
        if alert_id not in self.alert_events:
            return False
        
        alert = self.alert_events[alert_id]
        alert.acknowledged = True
        alert.acknowledged_by = acknowledged_by
        alert.acknowledged_at = datetime.now()
        
        logger.info(f"Alert acknowledged: {alert_id} by {acknowledged_by}")
        return True
    
    def resolve_alert(self, alert_id: str, resolved_by: str) -> bool:
        """解决告警"""
        if alert_id not in self.alert_events:
            return False
        
        alert = self.alert_events[alert_id]
        alert.resolved = True
        alert.resolved_by = resolved_by
        alert.resolved_at = datetime.now()
        
        logger.info(f"Alert resolved: {alert_id} by {resolved_by}")
        return True
    
    def get_alert_statistics(self, time_range: timedelta = timedelta(hours=24)) -> Dict[str, Any]:
        """获取告警统计"""
        end_time = datetime.now()
        start_time = end_time - time_range
        
        # 获取时间范围内的告警
        recent_alerts = [
            alert for alert in self.alert_events.values()
            if start_time <= alert.timestamp <= end_time
        ]
        
        # 按级别统计
        level_counts = defaultdict(int)
        for alert in recent_alerts:
            level_counts[alert.alert_level.value] += 1
        
        # 按摄像头统计
        camera_counts = defaultdict(int)
        for alert in recent_alerts:
            camera_counts[alert.camera_id] += 1
        
        # 计算确认率和解决率
        acknowledged_count = sum(1 for alert in recent_alerts if alert.acknowledged)
        resolved_count = sum(1 for alert in recent_alerts if alert.resolved)
        
        acknowledgment_rate = acknowledged_count / len(recent_alerts) if recent_alerts else 0
        resolution_rate = resolved_count / len(recent_alerts) if recent_alerts else 0
        
        return {
            'time_range': {
                'start': start_time.isoformat(),
                'end': end_time.isoformat()
            },
            'total_alerts': len(recent_alerts),
            'level_distribution': dict(level_counts),
            'camera_distribution': dict(camera_counts),
            'acknowledgment_rate': acknowledgment_rate,
            'resolution_rate': resolution_rate,
            'service_stats': self.stats.copy()
        }
    
    def update_filter_settings(self, settings: Dict[str, Any]):
        """更新过滤器设置"""
        if 'confidence_threshold' in settings:
            self.false_positive_filter.update_confidence_threshold(
                settings['confidence_threshold']
            )
        
        if 'frequency_threshold' in settings:
            self.false_positive_filter.update_frequency_threshold(
                settings['frequency_threshold']
            )
        
        logger.info("Filter settings updated")
    
    # ==================== 实时告警处理 ====================
    
    async def process_real_time_result(self, result_data: Dict[str, Any]) -> bool:
        """处理实时AI分析结果"""
        try:
            # 添加到事件队列进行处理
            await self._event_queue.put(result_data)
            return True
        except Exception as e:
            logger.error(f"处理实时结果失败: {e}")
            return False
    
    async def process_batch_results(self, results: List[Dict[str, Any]]) -> int:
        """批量处理实时结果"""
        success_count = 0
        
        for result in results:
            if await self.process_real_time_result(result):
                success_count += 1
        
        return success_count
    
    def add_real_time_rule(self, algorithm_name: str, rule_config: Dict[str, Any]) -> str:
        """添加实时告警规则"""
        rule_id = f"realtime_{algorithm_name}_{str(uuid4())[:8]}"
        
        # 为实时处理优化的规则配置
        conditions = []
        for cond_config in rule_config.get('conditions', []):
            condition = AlertCondition(
                field=cond_config['field'],
                operator=cond_config['operator'],
                value=cond_config['value'],
                duration=cond_config.get('duration', 0)  # 实时处理通常不需要持续时间
            )
            conditions.append(condition)
        
        # 创建规则引擎
        rule = AlertRuleEngine(
            rule_id=rule_id,
            rule_name=f"实时{algorithm_name}告警",
            conditions=conditions,
            alert_level=AlertLevel(rule_config.get('alert_level', 'medium')),
            cooldown_period=rule_config.get('cooldown_period', 60),  # 实时处理使用较短冷却期
            enabled=rule_config.get('enabled', True)
        )
        
        self.alert_rules[rule_id] = rule
        logger.info(f"添加实时告警规则: {rule_id} for {algorithm_name}")
        
        return rule_id
    
    def setup_default_real_time_rules(self):
        """设置默认实时告警规则"""
        # 行为分析实时规则
        behavior_rule_config = {
            'conditions': [
                {'field': 'behavior_type', 'operator': 'in', 'value': ['fighting', 'violence', 'emergency']},
                {'field': 'confidence', 'operator': '>=', 'value': 0.7}
            ],
            'alert_level': 'critical',
            'cooldown_period': 30
        }
        self.add_real_time_rule('behavior_analysis', behavior_rule_config)
        
        # 人群密度实时规则
        crowd_rule_config = {
            'conditions': [
                {'field': 'density', 'operator': '>', 'value': 0.8},
                {'field': 'confidence', 'operator': '>=', 'value': 0.6}
            ],
            'alert_level': 'high',
            'cooldown_period': 120
        }
        self.add_real_time_rule('crowd_density', crowd_rule_config)
        
        # 冲突检测实时规则
        conflict_rule_config = {
            'conditions': [
                {'field': 'conflict_detected', 'operator': '==', 'value': True},
                {'field': 'confidence', 'operator': '>=', 'value': 0.8}
            ],
            'alert_level': 'critical',
            'cooldown_period': 15
        }
        self.add_real_time_rule('conflict_detection', conflict_rule_config)
        
        # 垃圾检测实时规则
        waste_rule_config = {
            'conditions': [
                {'field': 'waste_count', 'operator': '>', 'value': 5},
                {'field': 'confidence', 'operator': '>=', 'value': 0.5}
            ],
            'alert_level': 'medium',
            'cooldown_period': 300
        }
        self.add_real_time_rule('waste_detection', waste_rule_config)
        
        logger.info("默认实时告警规则已设置")
    
    async def get_real_time_statistics(self) -> Dict[str, Any]:
        """获取实时告警统计"""
        # 获取最近1小时的统计
        end_time = datetime.now()
        start_time = end_time - timedelta(hours=1)
        
        recent_alerts = [
            alert for alert in self.alert_events.values()
            if start_time <= alert.timestamp <= end_time
        ]
        
        # 按算法统计
        algorithm_counts = defaultdict(int)
        for alert in recent_alerts:
            # 从元数据中提取算法名称
            algorithm_name = alert.metadata.get('algorithm_name', 'unknown')
            algorithm_counts[algorithm_name] += 1
        
        # 按摄像头统计
        camera_counts = defaultdict(int)
        for alert in recent_alerts:
            camera_counts[alert.camera_id] += 1
        
        # 计算处理速度
        processing_speed = len(recent_alerts) / 3600 if recent_alerts else 0  # 每秒处理数
        
        return {
            'time_window': '1小时',
            'total_real_time_alerts': len(recent_alerts),
            'algorithm_distribution': dict(algorithm_counts),
            'camera_distribution': dict(camera_counts),
            'processing_speed_per_second': processing_speed,
            'queue_size': self._event_queue.qsize(),
            'active_rules': len([r for r in self.alert_rules.values() if r.enabled]),
            'service_stats': self.stats.copy()
        }


# 全局智能告警服务实例
intelligent_alert_service = IntelligentAlertService()